package com.yanqu.road.server.cmd.union.cross.huaben;

import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.cross.UnionHuaBenProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;
import io.netty.channel.ChannelHandlerContext;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Cmd(code = Protocol.S_CROSS_UNION_HUA_BEN_SETTLE_REWARD_TO_MEMBER, desc = "话本结算成员奖励")
public class UnionHuaBenSettleMailScoreCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        UnionHuaBenProto.UnionHuaBenSettleMailScoreSyncMsg scoreSyncMsg = UnionHuaBenProto.UnionHuaBenSettleMailScoreSyncMsg.parseFrom(packet.getBytes());
        List<Long> userList = new ArrayList<>();

        for (UnionHuaBenProto.UnionHuaBenSettleMailScoreTemp scoreTemp : scoreSyncMsg.getUserScoreList()) {
            UserInfo userInfo = UserMgr.getUserInfoInRAM(scoreTemp.getUserId());
            if(userInfo != null){
                String title = MultipleLanguageMgr.getContent(MailManager.UNION_HUA_BEN_SETTLE_REWARD_SEND_TITLE, userInfo.getLanguage());
                String content = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.UNION_HUA_BEN_SETTLE_REWARD_SEND_CONTENT, userInfo.getLanguage()), scoreSyncMsg.getPingJia(), scoreTemp.getScore());
                MailManager.sendMail(userInfo.getUserId(), eMailType.DAILY.getValue(), GameConfig.UNION_STORY_SCORE_ID + "=" + scoreTemp.getScore(), content, title);

                userList.add(userInfo.getUserId());
            }
        }

        //跨服反馈
        UnionHuaBenProto.UnionHuaBenSettleMailScoreBackMsg.Builder backMsg = UnionHuaBenProto.UnionHuaBenSettleMailScoreBackMsg.newBuilder();
        backMsg.setWeekId(scoreSyncMsg.getWeekId());
        backMsg.addAllUserId(userList);
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_HUA_BEN_SETTLE_MAIL_BACK, backMsg));
    }
}
